package com.hs.app.action.search;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hs.app.service.ISearchService;
import com.hs.core.action.BaseAction;
import com.hs.core.cache.DictCacheUtil;
import com.hs.core.db.DBMgr;
@Controller  
public class SubjectTreeController  extends BaseAction {
    /**
	 * 
	 */
	private static final long serialVersionUID = -354434172898440670L;
	private static final Logger logger = Logger.getLogger(SubjectTreeController.class);
	private ISearchService searchService;
	@Autowired  
	public void setSearchService(ISearchService searchService) {
		this.searchService = searchService;
	}
	 /**
	  * 主题分类树
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/search/subjecttree.do")   
    public void subjecttree(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 long start = System.currentTimeMillis()/1000;
		 
		 StringBuilder builder = new StringBuilder();
		 Map datacache = new HashMap();
			builder.append("<?xml version='1.0' encoding='UTF-8'?>\n");
			builder.append("<tree id=\"0\">\n");
			DBMgr dbutil = this.getDbo(request); 
			builder.append("<item text=\"").append("主题分类").append("\" open=\"1\" id=\"").append("10000").append("\">");
			builder.append("\n"); 
			List alldataList = dbutil.queryList("select to_char(id) as idstr,to_char(pid) as pidstr,tagname,tagtype from CHD_TAGS where id>0 and isdelete=1 order by ordernum", null);
			for(int i=0;i<alldataList.size();i++){
				Map tag  = (Map)alldataList.get(i);
				String tagname = (String)tag.get("tagname");
				String tagid = (String)tag.get("idstr");
				String tagpid = (String)tag.get("pidstr");
				String tagtype =  tag.get("tagtype")+"";
//				SchdTags tagobj = new SchdTags();
//				tagobj.setId(new Long(tagid));
//				tagobj.setPid(new Long(tagpid));
//				tagobj.setTagname(tagname);
//				tagobj.setTagtype(new Long(tagtype));
//                if(null == datacache.get(tagpid)){
//                	List ptaglist = new TreeList();
//                	ptaglist.add(tagobj); 
//                	datacache.put(tagpid, ptaglist);
//                }else{
//                	List cachelist = (List)datacache.get(tagpid);
//                	cachelist.add(tagobj);
//                }
//				
			}
			//循环生成树 
			String onelevel = "select a.* from CHD_TAGS a where   pid=0   order by a.ordernum";
			List onelist = dbutil.queryList(onelevel, null);
			for(int j=0;j<onelist.size();j++){
				Map node = (Map)onelist.get(j);
				String name = node.get("TAGNAME")+"";  
				String id = node.get("ID")+""; 
				String tagtype = node.get("TAGTYPE")+""; 
				genTreeXml(builder,datacache,id,name,id,tagtype);
			}
			builder.append("</item>\n"); 
			builder.append("</tree>"); 
			logger.debug("start:" + start);
			
			//logger.info("builder：" + builder.toString());
		 
	    	try {
	    		 
				PrintWriter w = response.getWriter(); 
				 w.println(builder.toString());
				 w.flush();
				 w.close();
				 logger.debug("end:" + System.currentTimeMillis()/1000);
			} catch (IOException e) {
				 throw e;
			} 
			
		 
	 } 
	 
	 /**
	  * 异步加载主题分类树
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/search/maintree.do")   
    public void maintree(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 long start = System.currentTimeMillis()/1000;
		 
		 StringBuilder builder = new StringBuilder();
		 Map datacache = new HashMap();
			builder.append("<?xml version='1.0' encoding='UTF-8'?>\n");
			builder.append("<tree id=\"0\">\n");
			DBMgr dbutil = this.getDbo(request); 
			builder.append("<item text=\"").append("检索主题分类").append("\" nocheckbox=\"1\" open=\"1\" id=\"").append("10000").append("\">");
			builder.append("\n"); 
			List alldataList = dbutil.queryList("select a.*,to_char(a.id) as idstr from CHD_TAGS a where   pid=0   order by a.ordernum", null);
			for(int i=0;i<alldataList.size();i++){
				Map tag  = (Map)alldataList.get(i);
				String tagname = (String)tag.get("tagname");
				String tagid = (String)tag.get("idstr");
				String tagpid = (String)tag.get("pidstr");
				String tagtype =  tag.get("tagtype") + "";
//				ChdTags tagobj = new ChdTags();
//				tagobj.setId(new Long(tagid));
//				tagobj.setPid(new Long(tagpid));
//				tagobj.setTagname(tagname);
//                if(null == datacache.get(tagpid)){
//                	List ptaglist = new TreeList();
//                	ptaglist.add(tagobj); 
//                	datacache.put(tagpid, ptaglist);
//                }else{
//                	List cachelist = (List)datacache.get(tagpid);
//                	cachelist.add(tagobj);
//                }
				    builder.append("<item ");
//				    DictCacheUtil dictutil = DictCacheUtil.getInst();
//				    StringBuilder builderstr = new StringBuilder();
 					builder.append("  nocheckbox=\"1\" child=\"1\" id=\"").append(tagid).append("\" ");
					builder.append(">\n"); 
					builder.append("<itemtext><![CDATA["); 
				    builder.append(tagname); 
					builder.append("]]></itemtext>").append("\n");
					builder.append("<userdata name=\"tagtype\">").append(tagtype).append("</userdata>\n"); 
					
					builder.append("</item>\n"); 
				
			}
			  
			builder.append("</item>\n"); 
			builder.append("</tree>"); 
			logger.debug("start:" + start);
			
			//logger.info("builder：" + builder.toString());
			 
	    	try {
	    		 
				PrintWriter w = response.getWriter(); 
				 w.println(builder.toString());
				 w.flush();
				 w.close();
				 logger.debug("end:" + System.currentTimeMillis()/1000);
			} catch (IOException e) {
				 throw e;
			} 
			
		 
	 } 
	 /**
	  * 异步加载树节点
	  * @param request
	  * @param response
	  * @param modelMap
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	 @RequestMapping(value="/search/loadnode.do")   
    public void loadnode(HttpServletRequest request,
				HttpServletResponse response,ModelMap modelMap) throws ServletException, IOException {
		 long start = System.currentTimeMillis()/1000;
		 String pid = request.getParameter("id");
		 StringBuilder builder = new StringBuilder();
		 builder.append("<?xml version='1.0' encoding='UTF-8'?>\n");
		 builder.append("<tree id=\""+pid+"\">\n");
		 logger.debug("pid:"+pid);
		  DictCacheUtil dictutil = DictCacheUtil.getInst();
		 
		 Map datacache = new HashMap(); 
			DBMgr dbutil = this.getDbo(request);  
			List alldataList = dbutil.queryList("select a.*,to_char(a.id) as idstr,to_char((select count(*) from CHD_TAGS where pid=a.id)) as ischild from CHD_TAGS a where  isdelete =1 and pid=?   order by a.ordernum", new Object[]{pid});
			for(int i=0;i<alldataList.size();i++){
				Map tag  = (Map)alldataList.get(i);
				String tagname = (String)tag.get("tagname");
				String tagid = (String)tag.get("idstr"); 
				String ischild = (String)tag.get("ischild"); 
				String tagtype =  tag.get("tagtype") + ""; 
			    builder.append("<item "); 
				builder.append(" open=\"0\" ");
				if("0".equals(ischild)){
					builder.append(" child=\"0\" ");
				}else{
					builder.append(" child=\"1\" ");
				}
				builder.append("id=\"").append(tagid).append("\" ");
				builder.append(">\n"); 
				builder.append("<itemtext><![CDATA["); 
				 //查询中英文对照
			    if(null != dictutil.getSubjectcodeBycnKey(tagname)){
			    	builder.append(tagname).append("(").append(dictutil.getSubjectcodeBycnKey(tagname)).append(")");
			    }else{
			    	builder.append(tagname); 
			    }
				builder.append("]]></itemtext>").append("\n");
				builder.append("<userdata name=\"tagtype\">").append(tagtype).append("</userdata>\n"); 
				builder.append("</item>\n"); 
				
			}
			builder.append("</tree>\n");  
			 
			logger.debug("start:" + start);
			
			logger.info("builder：" + builder.toString());
		 
	    	try {
	    		 
				PrintWriter w = response.getWriter(); 
				 w.println(builder.toString());
				 w.flush();
				 w.close();
				 logger.debug("end:" + System.currentTimeMillis()/1000);
			} catch (IOException e) {
				 throw e;
			} 
			
		 
	 } 
	 
	 
	
	 private void genTreeXml(StringBuilder builder,Map datacache,String id,String tagname,String pid,String tagtype){ 
		    builder.append("<item ");
		    DictCacheUtil dictutil = DictCacheUtil.getInst();
		    StringBuilder builderstr = new StringBuilder();
		    
		   
		   // builder.append("\"");
		   // builder.append("<item text=\"&amp;lt;a href='' title=33333 &amp;gt;").append(tagname).append("&amp;lt;/a&amp;gt;\"");
		      
			builder.append(" open=\"1\" id=\"").append(id).append("\" ");
			builder.append(">\n"); 
			builder.append("<itemtext><![CDATA[");
			 //查询中英文对照
		    if(null != dictutil.getSubjectcodeBycnKey(tagname)){
		    	builder.append(tagname).append("(").append(dictutil.getSubjectcodeBycnKey(tagname)).append(")");
		    }else{
		    	builder.append(tagname);
		    	
		    }
			builder.append("]]></itemtext>").append("\n");
//			logger.debug("id:" + id);
//			logger.debug("pid:" + pid);
//			logger.debug("tagname:" + tagname);
//			logger.debug("haschild:" + datacache.get(pid));
			builder.append("<userdata name=\"tagtype\">").append(tagtype).append("</userdata>\n"); 
			if(null != datacache.get(pid)){
				List datalist = (List)datacache.get(pid);
				for(int i = 0;i<datalist.size();i++){
//					SchdTags o = (SchdTags)datalist.get(i);
//					String cid = o.getId()+"";
//					String ctagname = o.getTagname();
//					String tagt = o.getTagtype()+"";
//					genTreeXml(builder,datacache,cid,ctagname,cid,tagt);
				}
			} else{
				builder.append("</item>\n"); 
				return;
			}
			builder.append("</item>\n"); 
			
	 }
	 
}
